package cn.uncode.baas.server.internal.script;

import javax.script.Bindings;
import javax.script.Invocable;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import org.apache.commons.lang3.StringUtils;
import cn.uncode.baas.server.cache.SystemCache;
import cn.uncode.baas.server.internal.RequestMap;
import cn.uncode.baas.server.internal.log.Logger;
import cn.uncode.baas.server.internal.module.IModules;

public class ScriptExecuter {
	
	public static ScriptResult execute(RequestMap<String, Object> paramsMap, IModules modules, String script, String commonScript, String key, RequestMap<String, Object> head) throws NoSuchMethodException, ScriptException {
    	// 获取脚本引擎
		Logger.init();
		ScriptEngine scriptEngine = SystemCache.getScriptEngine(key);
		ScriptResult scriptResult = new ScriptResult();
		if(scriptEngine == null){
			ScriptEngineManager mgr = new ScriptEngineManager();
			scriptEngine = mgr.getEngineByName("javascript");
			Bindings bind = scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE);
			bind.put("log", Logger.getInstance());
			StringBuffer sb = new StringBuffer("var err=\"\";");
			sb.append(script);
			if(StringUtils.isNotEmpty(commonScript)){
				sb.append(commonScript);
			}
			scriptEngine.eval(sb.toString());
			SystemCache.setScriptEngine(key, scriptEngine);
		}
		Invocable invocable = (Invocable)scriptEngine;
		cn.uncode.baas.server.internal.context.ScriptContext context = 
				cn.uncode.baas.server.internal.context.ScriptContext.getCurrent();
		context.setAttribute("header", head);
		Object result = invocable.invokeFunction("main", paramsMap, context, modules);
		scriptResult.setResult(result);
		scriptResult.setErr(String.valueOf(scriptEngine.get("err")));
		scriptResult.setLogValue(Logger.getValue());
		return scriptResult;
	}

}
